{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 让openAI的api使用阿里云的服务器\n",
    "阿里百炼大模型API获取：https://bailian.console.aliyun.com/?apiKey=1#/api-key\n",
    "使用文档：https://help.aliyun.com/zh/model-studio/getting-started/what-is-model-studio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'我是来自阿里云的大规模语言模型，我叫通义千问。'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key=\"sk-0e687ddcf0164a6fb66c1096447223c4\",  # 阿里百炼大模型API获取：https://bailian.console.aliyun.com/?apiKey=1#/api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\" # 使用文档：https://help.aliyun.com/zh/model-studio/getting-started/what-is-model-studio\n",
    ")\n",
    "\n",
    "\n",
    "def llm(user_query):\n",
    "    system_prompt = f\"\"\"You are an expert at routing a user question to the relevant agent.\n",
    "    \"\"\"\n",
    "    query = user_query\n",
    "\n",
    "    completion = client.chat.completions.create(\n",
    "        model=\"qwen-plus\",\n",
    "        messages=[{'role': 'system', 'content': system_prompt},\n",
    "                  {'role': 'user', 'content': query}],\n",
    "        )\n",
    "    return completion.choices[0].message.content\n",
    "\n",
    "llm(\"你是什么模型？\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用http request而非openai库来访问大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "要了解今天的新闻，通常可以从以下几个方面获取：\n",
      "\n",
      "1. **国际新闻**：可以关注全球重要事件，如政治、经济、军事等方面的最新动态。\n",
      "2. **国内新闻**：包括国家政策、社会热点、科技发展等领域的信息。\n",
      "3. **本地新闻**：关注所在城市或地区的具体事件，如交通、天气、社区活动等。\n",
      "4. **娱乐新闻**：明星动态、电影上映、音乐发布等文化娱乐领域的内容。\n",
      "5. **体育新闻**：各类体育赛事的结果和相关话题讨论。\n",
      "\n",
      "为了提供更具体的信息，你可以告诉我你感兴趣的新闻类型或者地区，这样我可以为你查找更详细的内容。同时，请确保从可靠的来源获取信息，以保证新闻的真实性和准确性。如果你有特定的新闻源偏好，也可以一并告知。\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "# 阿里云百炼大模型的 API Key 和 API URL\n",
    "api_key = \"sk-0e687ddcf0164a6fb66c1096447223c4\"  # 替换为你的阿里云百炼大模型 API Key\n",
    "api_url = \"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions\"  # API 的完整路径\n",
    "\n",
    "def llm(user_query):\n",
    "    system_prompt = \"\"\"你会搜索网络，并给出答案.\"\"\"\n",
    "    query = user_query\n",
    "\n",
    "    # 构造请求的 payload\n",
    "    payload = {\n",
    "        \"model\": \"qwen-plus\",\n",
    "        \"max_tokens\": 8192,\n",
    "        \"enable_search\": True,\n",
    "        \"messages\": [\n",
    "            {\"role\": \"system\", \"content\": system_prompt},\n",
    "            {\"role\": \"user\", \"content\": query}\n",
    "        ]\n",
    "    }\n",
    "\n",
    "    # 设置请求的 headers\n",
    "    headers = {\n",
    "        \"Content-Type\": \"application/json\",\n",
    "        \"Authorization\": f\"Bearer {api_key}\"\n",
    "    }\n",
    "\n",
    "    # 发送 POST 请求\n",
    "    response = requests.post(api_url, headers=headers, data=json.dumps(payload))\n",
    "\n",
    "    # 检查响应状态\n",
    "    if response.status_code != 200:\n",
    "        raise Exception(f\"HTTP error! status: {response.status_code}, response: {response.text}\")\n",
    "\n",
    "    # 解析响应内容\n",
    "    response_data = response.json()\n",
    "    return response_data[\"choices\"][0][\"message\"][\"content\"]\n",
    "\n",
    "# 测试函数\n",
    "result = llm(\"今天微博有什么大事发生？\")\n",
    "print(result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
